package communication;

import java.util.Vector;
import meterAPI.Communicator;

/**
 * Uses the Communicator object to receiver and store message
 * @author Pavel
 *
 */
public class Receiver extends Thread {
	private Vector<String> messageQueue;
	private Communicator communicator;

	public Receiver(Communicator communicator) {
		this.communicator = communicator;
		this.messageQueue = new Vector<String>();
	}

	public String getMessage() {
		return messageQueue.remove(0);
	}

	public boolean isMessageQueueEmpty() {
		return messageQueue.isEmpty();
	}

	/**
	 * Returns the received message from the Communicator
	 * 
	 * @throws Exception
	 */
	public synchronized String receive() throws Exception {
		String res = "";
		while (!res.trim().endsWith("$")) {
			Thread.sleep(100);		
			String s = communicator.recvMessage();
		
			res = res + s;

		}
		return res;
	}
	
	/**
	 * Runs on an infinite loop
	 */
	public void run() {
		while (true) {

			try {
				String message = receive();
				System.out.println("[SmartMeter] Received: " + message);
				messageQueue.add(message);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
